package com.exm.collectcodenew.juc.aqs;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    private static final int threadCount = 200;
    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < threadCount; i++) {
            final int threadNum =i;
            exec.execute(()->{
                try {
                    semaphore.acquire(1);//获取一个许可
                    test(threadNum);
                    semaphore.release(1);//释放一个许可
//                    if(semaphore.tryAcquire()){
//                        test(threadNum);
//                        semaphore.release();
//                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            });
        }

    }
    private static void test(int threadNum) throws InterruptedException{
        System.out.println(threadNum);
        Thread.sleep(1000);
    }
}
